<?php
declare (strict_types=1);

namespace app\controller;

use app\validate\User as UserValidate;
use app\model\User as UserModel;
use app\model\Tags as TagsModel;
use app\model\Area as AreaModel;

use app\BaseController;
use Exception;
use think\App;
use think\Request;
use think\Response;

class User extends BaseController
{
    protected UserModel $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new UserModel();
    }

    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index()
    : Response
    {
        $params = $this->request->param();
        $where  = [];
        if (!empty($params['username'])) {
            $where[] = [ 'username' , 'like' , "%{$params['username']}%", ];
        }
        try {
            $count   = $this->model->where($where)->count();
            $query   = $this->model->where($where)->page($this->page , $this->pageSize);
            $orderBy = 'id DESC';
            if (!empty($params['order']) && !empty($params['orderField'])) {
                $orderBy = $params['orderField'] . " " . $params['order'];
            }
            $list = $query->order($orderBy)->select()->toArray();
            $data   = [];
            foreach ($list as $item) {
                if (!empty($item['tags'])) {
                    $item['tags'] = (new TagsModel())->whereIn('id' , $item['tags'])->column('title');
                }
                $data[] = $item;
            }
            return $this->success('success' , [
                'total'    => $count ,
                'page'     => $this->page ,
                'pageSize' => $this->pageSize ,
                'list'     => $data ,
            ]);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create()
    : Response
    {
        $params   = $this->request->param();
        $validate = new UserValidate();
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }
        $user = $this->model::create($params);
        if ($user->isEmpty()) {
            return $this->error('create failed');
        }

        return $this->success('success' , $user->toArray());
    }

    /**
     * 显示指定的资源
     *
     * @param Request $request
     *
     * @return Response
     */
    public function read(Request $request)
    : Response {
        $id = $request->param('id/d' , 0);
        if (!$id) {
            return $this->error('parameter error');
        }
        try {
            $data = $this->model->find($id);
            if ($data->isEmpty()) {
                return $this->error('data does not exist');
            }
            $data->tags_list = (new TagsModel())->whereIn('id' , $data['tags'])->column('title');
            $data->area_list = (new AreaModel())->whereIn('id' , $data['area'])->column('cname');
            return $this->success('success' , $data->toArray());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function edit(Request $request)
    : Response {
        $params = $request->param();
        if (empty($params['id'])) {
            return $this->error('parameter error');
        }
        try {
            $info = $this->model->find($params['id']);
            if ($info->isEmpty()) {
                return $this->error('data does not exist');
            }
            $fields = ['id','username' , 'password' , 'email' , 'nickname' , 'avatar' ,'area', 'state' , 'sex' , 'age' , 'tags', 'address' , 'remark' ];
            foreach ($params as $key => $value) {
                if (in_array($key , $fields, true)) {
                    $info->$key = $value;
                }
            }
            $info->save();
            return $this->success('success' , $info->toArray());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param Request $request
     *
     * @return Response
     */
    public function delete(Request $request)
    : Response {
        $id = $request->param('id/d' , 0);
        if (empty($id)) {
            return $this->error('parameter error');
        }
        try {
            $result = $this->model::destroy($id);
            if ($result) {
                return $this->success('success' , $id);
            }

            return $this->error();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
